﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Serialization;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CAD33Controller : CADFinishController
    {
        private JavaScriptSerializer m_jss = new JavaScriptSerializer();
        bool m_isErp = false;
        #region  原有的
        /// <summary>
        /// 导入生产单  
        /// </summary>   
        /// <param name="json">id process go upload file文件名/文件夹名 extname扩展名  TDxml文件路径 </param>
        [HttpPost, Route("cad33/Finish")]
        public string Finish(dynamic json)
        {
            WriteLog("cad33/Finish", "json:" + json.ToString(), true);
            if (json == null)
                return ReturnError(201, "没有可执行参数");
            string filename = json.file.ToString();
            m_isErp = Convert.ToInt32(json.id) == 0 ? false : true;

            WriteLog("cad33/Finish", "m_isErp:" +m_isErp, true);

            string dirName = "";
            if (!m_isErp)
                dirName = json.name.ToString();
            else
                dirName = filename.Substring(0,filename.LastIndexOf("."));
            int upload = Convert.ToInt32(json.upload);

            int loginid = GetCrrentIDByToken();
            User user = GetUserByLoginID(loginid);
            WriteDebug("cad33/Finish", "2"+ dirName);

            if (user == null)
                return ReturnError(201, "不存在当前工号为" + loginid + "的用户");
            string xmlpath = GetPCPath(dirName) + "\\" + filename;

            WriteDebug("cad33/Finish", xmlpath);
            if (!File.Exists(xmlpath))
                return ReturnError(201, "找不到路径" + xmlpath);

            #region  读取xml文件数据 样式名，订单号，ERP中的ID(orderId),生产件数
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlpath);

            WriteDebug("cad33/Finish", "4");

            XmlNode xmlModel = doc.GetElementsByTagName("modelName")[0];
            string modelName = xmlModel == null ? "" : xmlModel.InnerText;
            //序列号 
            XmlNode xmlOrder = doc.GetElementsByTagName("orderName")[0];
            string orderName = xmlOrder == null ? "" : xmlOrder.InnerText;

            XmlNode xmlnode = doc.GetElementsByTagName("orderID")[0];
            string orderId = "0";
            if (xmlnode != null)
                orderId = xmlnode.InnerText;
            int number = Convert.ToInt32(doc.GetElementsByTagName("number")[0].InnerText);

            WriteDebug("cad33/Finish", "5");

            #endregion
            try
            {
                if (string.IsNullOrEmpty(modelName) || string.IsNullOrEmpty(orderName) || number < 0)
                    return ReturnError(201, "给的数据不完整,样式名:" + modelName + "，订单号:" + orderName + "，ERP中的ID:" + orderId + ",生产件数:" + number);
                WriteDebug("cad33/Finish", "6");
                if (!m_isErp && CheckOrdername(orderName))
                {
                    WriteDebug("cad33/Finish", orderName + "该生产单号已经存在");
                    return ReturnError(201, orderName + "该生产单号已经存在");
                }
                else
                {
                    int rs = 0;
                    WriteDebug("cad33/Finish", orderName + "开始区别处理");
                    if (m_isErp)
                        rs = AddOrderAndPC(user, modelName, orderName, orderId, number, doc);
                    else
                        rs = AddOrderAndPC(user, modelName, orderName, orderId, number, doc);
                    if (rs == 0)
                    {
                        WriteDebug("cad33/Finish", "7");
                        return ReturnError(201, "数据操作出错");
                    }
                    if (rs == -1)
                    {
                        WriteDebug("cad33/Finish8", "没有相应的样式信息，没有找到名为" + modelName + "的modelid");
                        return ReturnError(201, "没有相应的样式信息 ");
                    }
                }
            }
            catch (Exception ex)
            {
                WriteDebug("cad33/Finish8 异常：", ex.Message);
            }

            return ReturnError(200, "OK");
        }

        #region  兼容
        private int AddOrderAndPC(User user, string modelName, string orderName, string orderID, int number, XmlDocument doc)
        {
            try
            {
                List<SQLCommand> cmds = new List<SQLCommand>();

                MyOrder myOrder = AddOrder(user, cmds, modelName, orderName, orderID, number, doc);

                PCHandle(cmds, user, myOrder);
                int rtn = SQLCommand.ExecTran(cmds);

                if (rtn == 1)
                {
                    WriteDebug("AddOrderAndPC", "新增Order与PC记录成功 rtn:" + rtn);
                    //压缩后产生数据
                    AddTask(33, myOrder.id);
                    AddLSH(doc, myOrder.id);
                }
                return rtn;
            }
            catch (Exception e)
            {
                WriteLog("AddOrderAndPC", e.Message);
                return 0;
            }

        }
        /// <summary>
        /// 流畅处理  批量修改  一个一个新增
        /// </summary>
        private void PCHandle(List<SQLCommand> cmds,User user,MyOrder myOrder)
        {
            SQLCommand sc = new SQLCommand();
            string sql = "";
            if (!m_isErp)
            {
                #region  添加流程     
                sql = "insert into PC_tb(path,pc_id,PLID,rank,maxStep,step,model_id,grouping) values(";
                sc = new SQLCommand();
                sc.AddInsert("@path", myOrder.name);
                sc.AddInsert("@pcid", myOrder.id);
                sc.AddInsert("@plid", user.PLID);
                sc.AddInsert("@rank", Convert.ToInt32(myOrder.rank));
                sc.AddInsert("@maxstep", 33);
                sc.AddInsert("@step", GetNextProcessID(user.PLID, 33));
                sc.AddInsert("@model_id", myOrder.ModelId);
                sc.AddInsert("@pcgrouping", user.grouping);
                sc.JoinSql(sql);
                cmds.Add(sc);
                WriteDebug("AddOrderAndPC", "PC_tb插入语句" + sql);
                #endregion
            }
            else
            {
                sql = "update PC_tb set maxStep=33,step=@step where pc_id=@pcid";
                sc = new SQLCommand(sql);
                sc.Add("@step", GetNextProcessID(user.PLID, 33));
                sc.Add("@pcid", myOrder.id);
                cmds.Add(sc);
                WriteDebug("AddOrderAndPC", "PC_tb修改语句" + sql);
            }

        }

        /// <summary>
        /// 批量导入与非批量导入的区别处理
        /// </summary>
        /// <param name="user"></param>
        /// <param name="cmds"></param>
        /// <param name="modelName"></param>
        /// <param name="orderName"></param>
        /// <param name="orderID"></param>
        /// <param name="number"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private MyOrder AddOrder(User user, List<SQLCommand> cmds, string modelName, string orderName, string orderID, int number, XmlDocument doc)
        {
            MyOrder order = null;
            try
            {
                string[] minfo = GetMaterialInfo(doc);
                XmlNode rank = doc.GetElementsByTagName("isAlarm")[0];
                XmlNode remark = doc.GetElementsByTagName("depiction")[0];
                XmlNode nature = doc.GetElementsByTagName("schemetype")[0];
                XmlNode finishTime = doc.GetElementsByTagName("overTime")[0];
                XmlNode custnameXml = doc.GetElementsByTagName("customerName")[0];
                XmlNode erpname = doc.GetElementsByTagName("erpName")[0];
                int isalerm = 0;
                if (rank != null)
                    isalerm = Convert.ToInt32(rank.InnerText);
                if (!m_isErp)
                {
                    #region  新增订单  
                    string sql = "";
                    SQLCommand sc = new SQLCommand("select id from Model_tb where name=@name", "@name", modelName);
                    string res = sc.ExecuteScalar();
                    if (res == null)
                        return null;//没有响应的款式信息  样式信息   
                    int modelid = Convert.ToInt32(res);
                    int id = GetNewSafeID(user.login_id);
                    WriteDebug("AddOrderAndPC", "modelid:" + modelid);
                    //PLID是当前用户对应的吗  暂时这样做处理  model_id 根据样板名从Model_tb表中获取 erpid为表中的orderID erpname记录erpName lsh流水号暂认为0
                    //流水号  LSH LSH_tb中erpID指用户id即工号 根据用户id获取流水号
                    if (SQLCommand.IsOracle)
                        sql = "insert into Order_tb values(@orderid,@oname,@createid,to_date(@createtime,'yyyy-mm-dd hh24:mi:ss'),to_date(@finishtime,'yyyy-mm-dd hh24:mi:ss'),@plid,@modelid,0,' ',@erpid,@erpname,' ',' ',0,0,0,@lsh,0,@onumber,1,@erpcustname,@mcode,@mcolor,@nature,@rank,@remark,@width)";
                    else
                        sql = "insert into Order_tb values(@orderid,@oname,@createid,@createtime,@finishtime,@plid,@modelid,0,' ',@erpid,@erpname,' ',' ',0,0,0,@lsh,0,@onumber,1,@erpcustname,@mcode,@mcolor,@nature,@rank,@remark,@width)";
                    sc = new SQLCommand(sql);
                    sc.Add("@orderid", id);
                    sc.Add("@oname", orderName);
                    sc.Add("@createid", user.login_id);
                    sc.Add("@createtime", DateTime.Now, true);
                    if (finishTime == null)
                        sc.Add("@finishtime", DateTime.Now.AddMonths(2), true);
                    else
                    {
                        string overtimt = finishTime.InnerText;
                        sc.Add("@finishtime", overtimt == null ? DateTime.Now.AddMonths(2) : Convert.ToDateTime(overtimt.Substring(0, 10)), true);
                    }
                    sc.Add("@plid", user.PLID);
                    sc.Add("@modelid", modelid);
                    sc.Add("@erpid", orderID);
                    sc.Add("@erpname", erpname == null ? "" : erpname.InnerText);
                    sc.Add("@lsh", 0);
                    sc.Add("@onumber", 0);
                    sc.Add("@erpcustname", custnameXml == null ? "" : custnameXml.InnerText);
                    sc.Add("@mcode", minfo[0]);
                    sc.Add("@mcolor", minfo[1]);
                    sc.Add("@nature", nature == null ? "" : nature.InnerText);
                    sc.Add("@rank", isalerm);
                    sc.Add("@remark", remark == null ? "" : remark.InnerText);
                    sc.Add("@width", Convert.ToDouble(minfo[2]));
                    cmds.Add(sc);
                    WriteDebug("AddOrderAndPC", "Order插入语句" + sql);
                    #endregion
                    order = new MyOrder()
                    {
                        id = id,
                        ModelId = modelid,
                        name = orderName,
                        modelName = modelName,
                        mCode = minfo[0],
                        mColor = minfo[1],
                        o_creater_id = user.login_id,
                        bind_id = 0,
                        erp_custname = custnameXml == null ? "" : custnameXml.InnerText,
                        erp_name = erpname == null ? "" : erpname.InnerText,
                        rank = isalerm,
                        nature = nature == null ? "" : nature.InnerText,
                        remark = remark == null ? "" : remark.InnerText,
                        width = Convert.ToDouble(minfo[2]),
                        finish_time = finishTime.InnerText == null ? DateTime.Now.AddMonths(2) : Convert.ToDateTime(finishTime.InnerText.Substring(0, 10)),
                        quantity = 0,
                        LSH = 0
                    };
                }
                else
                {
                    string sql = "select Order_tb.id,Order_tb.name as name,Model_tb.id as ModelId,Model_tb.name as modelName,o_creater_id,finish_time,bind_id,erp_id,erp_name,LSH,quantity,erp_custname,mCode,mColor,rank,nature,remark,width from Order_tb join Model_tb on o_model_id = Model_tb.id where Order_tb.Name = @orderName";
                    SQLCommand sc = new SQLCommand(sql, "@orderName", orderName);
                    order = AssistFun.DataRowToObject<MyOrder>(sc.ExecuteOneRow());
                }
            }
            catch (Exception ex)
            {
                WriteDebug("AddOrder", "异常:" + ex.Message);
                throw;
            }
            return order;
        }
        #endregion



        private string[] GetMaterialInfo(XmlDocument doc)
        {
            XmlNodeList fabrics = doc.GetElementsByTagName("fabric");
            //物料可能有多个或者没有暂时取第一个 客户名没有暂时为空
            string mcode = "";
            string mcolor = "";
            string width = "";
            if (fabrics.Count > 0)
            {
                for (int i = 0; i < 1; i++)
                {
                    foreach (XmlNode item in fabrics[i])
                    {
                        if (item.Name.Equals("code"))
                            if (item.InnerText != null)
                                mcode = item.InnerText;
                        if (item.Name.Equals("color"))
                            if (item.InnerText != null)
                                mcolor = item.InnerText;
                        if (item.Name.Equals("width"))
                            width = item.InnerText == null ? "0" : item.InnerText;

                        //if (item.Name.Equals("custname")) 
                        //    if (item.InnerText != null)
                        //        erpcustname = item.InnerText;
                    }
                }
            }

            return new string[] { mcode, mcolor, width };
        }

        /// <summary>
        /// 添加流水号
        /// </summary>
        /// <param name="erpId">erpids是XML中的person的ID   用户（人）的ID	整数</param>     
        /// <param name="orderid">流程</param>  
        /// <param name="usrename">用户的姓名	最大6个字符</param>
        /// <param name="pod">Pod文件的文件名</param>
        private void AddLSH(XmlDocument doc, int orderid)
        {
            try
            {
                XmlNodeList persons = doc.GetElementsByTagName("person");
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "insert into LSH_tb values(@orderid,@name,@erpid,@pod,@lsh,@copys)";

                if (persons.Count > 0)
                {
                    for (int i = 0; i < persons.Count; i++)
                    {
                        SQLCommand sc = new SQLCommand(sql);
                        sc.Add("@orderid", orderid);
                        foreach (XmlNode node in persons[i])
                            AddLSH(node, sc);
                        sc.Add("@lsh", 0);
                        cmds.Add(sc);
                    }
                    if (SQLCommand.ExecTran(cmds) == 1)
                    {
                        sql = "select sum(tdMulit) from LSH_tb where order_id=" + orderid;
                        SQLCommand sc = new SQLCommand(sql);
                        string total = sc.ExecuteScalar();
                        if (total != null)
                        {
                            sql = "update Order_tb set quantity=@countPer where id=" + orderid;
                            sc = new SQLCommand(sql, "@countPer", Convert.ToInt32(total));
                            sc.ExecuteNonQuery();
                        }

                        WriteDebug("AddLSH", "新增成功");
                    }
                    else
                        WriteDebug("AddLSH", "新增失败");
                }
            }
            catch (Exception e)
            {
                WriteDebug("AddLSH", "新增LSH记录失败," + e.Message);
            }

        }

        private void AddLSH(XmlNode node, SQLCommand sc)
        {
            if (node.Name.Equals("ID"))
            {
                AddInt(sc, "@erpid", node);
            }
            else if (node.Name.Equals("name"))
            {
                AddString(sc, "@name", node);
            }
            else if (node.Name.Equals("pod"))
            {
                AddInt(sc, "@pod", node);
            }
            else if (node.Name.Equals("copys"))
                AddInt(sc, "@copys", node);
        }
        #endregion


    }
}
